package com.aidong.search.action;

import java.text.SimpleDateFormat;
import java.util.*;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.json.annotations.JSON;
import org.springframework.beans.factory.annotation.Autowired;

import com.aidong.activity.entity.Member;
import com.aidong.login.biz.MemberLocationReportBiz;
import com.aidong.myprofile.biz.MyPersonalMsgBiz;
import com.aidong.myprofile.entity.MyPersonalMsg;
import com.aidong.search.biz.SearchBiz;
import com.aidong.search.entity.NearbyPersonEntity;
import com.aidong.util.CountDistance;
import com.aidong.util.MyPersonalInfoUtil;
import com.aidong.util.PageUtil;
import com.aidong.util.ReadPropertiesUtil;
import com.aidong.util.SortUtil;
import com.opensymphony.xwork2.ModelDriven;

/**
 * 附近的人action
 * 
 * @author user
 *
 */
@ParentPackage("json")
@Namespace("/")
public class SearchAction implements ModelDriven<NearbyPersonEntity> {

	private NearbyPersonEntity person;
	
	private MemberLocationReportBiz locationReportBiz;
	
	private MyPersonalMsgBiz personalMsgBiz; // 个人信息service
	
	private int pageCurrent; // 当前页

	public void setPageCurrent(int pageCurrent) {
		this.pageCurrent = pageCurrent;
	}

	@Override
	public NearbyPersonEntity getModel() {
		if (person == null) {
			person = new NearbyPersonEntity();
		}
		return person;
	}

	private SearchBiz searchBiz;

	@Autowired
	public void setLocationReportBiz(MemberLocationReportBiz locationReportBiz) {
		this.locationReportBiz = locationReportBiz;
	}

	@Autowired
	public void setSearchBiz(SearchBiz searchBiz) {
		this.searchBiz = searchBiz;
	}

	/**
	 * 个人信息service
	 * @param personalMsgBiz
	 */
	@Autowired
	public void setPersonalMsgBiz(MyPersonalMsgBiz personalMsgBiz) {
		this.personalMsgBiz = personalMsgBiz;
	}
	
	private Map<String, Object> map;

	@JSON
	public Map<String, Object> getMap() {
		return map;
	}

	private List<Map<String, Object>> persons;

	@JSON
	public List<Map<String, Object>> getPersons() {
		return persons;
	}

	/**
	 *  附近的人
	 *
	 * @return
	 */
	@Action(value = "searchPerson", results = { @Result(name = "succ", type = "json", params = {
			"root", "map" }) })
	public String searchPerson() {
		/*try {
			int idongId = person.getIdongId();

			String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
			String hour = new SimpleDateFormat("HH").format(new Date());
			
			// 记录用户活跃度
			if(idongId > 0){
				// 是否在当天某时已有记录
				Map<String, Object> memberMap = new HashMap<String, Object>();
				memberMap.put("date", date);
				memberMap.put("menuType", 3);
				memberMap.put("idongId", idongId);
				Map<String, Object> userCountMap = locationReportBiz.getFunctionUseCount(memberMap);
				if(userCountMap != null){
					// 修改用户活跃数 
					int userCount = Integer.parseInt(userCountMap.get("count") + "");
					userCountMap.put("liveCount", userCount + 1);
					locationReportBiz.editFunctionUseCount(userCountMap);
				}else{
					// 记录用户活跃数
					memberMap.put("liveCount", 1);
					memberMap.put("liveType", 2);
					locationReportBiz.addFunctionUseLiveness(memberMap);
				}
			}
			// 是否在当天某时已有记录
			Map<String, Object> useMap = new HashMap<String, Object>();
			useMap.put("date", date);
			useMap.put("menuType", 3);
			useMap.put("hour", hour);
			Map<String, Object> countMap = locationReportBiz.getFunctionUseCount(useMap);
			if(countMap != null){
				// 修改使用活跃数
				int recordCount = Integer.parseInt(countMap.get("count") + "");
				useMap.put("liveCount", recordCount + 1);
				locationReportBiz.editFunctionUseCount(useMap);
			}else{
				// 记录使用活跃度
				useMap.put("liveCount", 1);
				useMap.put("liveType", 1);
				locationReportBiz.addFunctionUseLiveness(useMap);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}*/
		
		double lon = person.getLon(); // 纬度
		double lat = person.getLat(); // 经度
		int idongId = person.getIdongId(); // 爱动号
		
		// 条件筛选参数
		String gender = person.getGender(); // 性别
		String region = person.getRegion(); // 地区
		String age = person.getAge(); 
		String height = person.getHeight();
		String constellation = person.getConstellation(); // 星座
		String BMH = person.getBMH(); // 三围
		String personalLables = person.getPersonalLables(); // 个性标签
		String sportLable = person.getSportLables(); // 运动标签
		String charmPart = person.getCharmPart(); // 魅力部位
		String sportHz = person.getSportHz(); // 运动频次
		
		map = new HashMap<String, Object>();
		int totalCount = 0;
		try {
			if(idongId == 0){
				map.put("code", 0);
				map.put("msg", "请先登陆");
				return "succ";
			}
			if(lon > 0 && lat > 0){
				// 更新我的位置
				Map<String, Object> reportMap = new HashMap<String, Object>();
				reportMap.put("latitude", lat);
				reportMap.put("longitude", lon);
				reportMap.put("idongId", idongId);
				locationReportBiz.editMyLocation(reportMap);
				
				// 分页
				Map<String, Object> locationMap = PageUtil.page(9, pageCurrent);
				totalCount = Integer.parseInt(locationMap.get("pageCurrent").toString());
				locationMap.put("lon", lon);
				locationMap.put("lat", lat);
				
				// 运动频次
				locationMap.put("sportHz", sportHz);
				
				// 性别
				locationMap.put("gender", gender);
				
				// 地区
				if(!"".equals(region) && region != null){
					locationMap.put("region", "%" + region + "%");
				}else{
					locationMap.put("region", region);
				}
				
				// 身高
				locationMap.put("height", height);
				if(!"".equals(height) && height != null){
					String[] arrHeight = height.split("-"); // 身高范围
					if(arrHeight.length > 0){
						locationMap.put("minHeight", arrHeight[0]);
						locationMap.put("maxHeight", arrHeight[1]);
					}
				}

				// 年龄
				locationMap.put("age", age);
				if(!"".equals(age) && age != null){
					String[] arrAge = age.split("-"); // 年龄范围
					int minAge = Integer.parseInt(arrAge[0]);
					int maxAge = Integer.parseInt(arrAge[1]);
					Calendar cal = Calendar.getInstance();
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					cal.setTime(sdf.parse(sdf.format(cal.getTime())));
					cal.add(Calendar.YEAR, -minAge);
					locationMap.put("maxBirthday", cal.getTime());
					cal.add(Calendar.YEAR, minAge-maxAge-1);
					cal.add(Calendar.DATE, 1);
					locationMap.put("minBirthday", cal.getTime());
				}

				// 星座
				locationMap.put("constellation", constellation);
				if(!"".equals(constellation) && constellation != null){
					String dt[] = MyPersonalInfoUtil.getConstellationDay(constellation);
					locationMap.put("minBirthMonthDay", dt[0]);
					locationMap.put("maxBirthMonthDay", dt[1]);
				}
				
				// 三围
				locationMap.put("BWH", BMH);
				if(!"".equals(BMH) && BMH != null){
					String[] arrBWH = BMH.split("/");
					if(arrBWH.length > 0){
						
						String[] bwhBust = arrBWH[0].split("-"); // 胸围范围
						String[] bwhWaist = arrBWH[1].split("-"); // 腰围范围
						String[] bwhHip = arrBWH[2].split("-"); // 臀围范围
						
						locationMap.put("minBust", bwhBust[0]);
						locationMap.put("maxBust", bwhBust[1]);
						
						locationMap.put("minWaist", bwhWaist[0]);
						locationMap.put("maxWaist", bwhWaist[1]);
						
						locationMap.put("minHip", bwhHip[0]);
						locationMap.put("maxHip", bwhHip[1]);
					}
					
				}
				
				// 个性标签
				locationMap.put("personals", personalLables);
				if(!"".equals(personalLables) && personalLables != null){
					String personLable[] = personalLables.split(",");
					if(personLable.length > 0){
						List<Map<String, Object>> personLables = new ArrayList<Map<String, Object>>();
						for (int i = 0; i < personLable.length; i++) {
							Map<String, Object> paraMap = new HashMap<String, Object>();
							paraMap.put("personLable",personLable[i]);
							personLables.add(paraMap);
						}
						locationMap.put("personLables", personLables);
					}
				}
				
				// 运动标签
				locationMap.put("sportLable", sportLable);
				if(!"".equals(sportLable) && sportLable != null){
					String sportLables[] = sportLable.split(",");
					if(sportLables.length > 0){
						List<Map<String, Object>> sportLableList = new ArrayList<Map<String, Object>>();
						for (int i = 0; i < sportLables.length; i++) {
							Map<String, Object> sportMap = new HashMap<String, Object>();
							sportMap.put("sportLable", sportLables[i]);
							sportLableList.add(sportMap);
						}
						locationMap.put("sportLableList", sportLableList);
					}
				}
				
				// 魅力部位
				locationMap.put("charmPart", charmPart);
				if(!"".equals(charmPart) && charmPart != null){
					String charmParts[] = charmPart.split(",");
					if(charmParts.length > 0){
						List<Map<String, Object>> charmPartList = new ArrayList<Map<String, Object>>();
						for (int i = 0; i < charmParts.length; i++) {
							Map<String, Object> charmMap = new HashMap<String, Object>();
							charmMap.put("charmLable", charmParts[i]);
							charmPartList.add(charmMap);
						}
						locationMap.put("charmPartList", charmPartList);
					}
				}
				
				List<NearbyPersonEntity> personData = searchBiz.searchNearbyPerson(locationMap);
				
				if(personData.size() > 0){
					
					if(personData.size() > 0){
						HashMap<Integer,NearbyPersonEntity> perosnLocationMap=new HashMap<Integer,NearbyPersonEntity>();
						for (NearbyPersonEntity person : personData) {
							perosnLocationMap.put(person.getIdongId(), person);
						}

						map = new HashMap<String, Object>();
						map.put("list", perosnLocationMap.keySet());
						persons = searchBiz.getNearbyPersonInfo(map);

						for (Map<String, Object> memberMap : persons) {
							Map<String, Object> taskTags = personalMsgBiz.selectTaskTags(idongId);
							memberMap.put("task1", Integer.parseInt(taskTags.get("task1").toString()));
							memberMap.put("task2", Integer.parseInt(taskTags.get("task2").toString()));
							memberMap.put("task3", Integer.parseInt(taskTags.get("task3").toString()));
							String headUrl = memberMap.get("headUrl") + "";
							if(!"".equals(headUrl) && headUrl != null){
								memberMap.put("headUrl", ReadPropertiesUtil.getIMGREAD(headUrl));
							}else{
								memberMap.put("headUrl", "");
							}
							double discance = CountDistance.distance(lon,lat,perosnLocationMap.get(memberMap.get("idongId")).getLon(),perosnLocationMap.get(memberMap.get("idongId")).getLat());
							int	dis = (int) Math.rint(discance); // 四舍五入取整数
							int distance = dis/1000;
							memberMap.put("distance", (int) dis);
							if(distance < 1){
								if(dis <= 100){
									memberMap.put("coordinate", "<100m"); // 相距距离
								}else if(100 < dis && dis <= 500){
									memberMap.put("coordinate", "<500m"); // 相距距离
								}else if(500 < dis && dis <= 800){
									memberMap.put("coordinate", "<800m"); // 相距距离
								}else{
									memberMap.put("coordinate", dis + " m"); // 相距距离
								}
							}else{
								memberMap.put("coordinate", distance + " km"); // 相距距离
							}

							Map<String, Object> paraMap = new HashMap<String, Object>();
							paraMap.put("idongId", idongId); // 关注人
							paraMap.put("tionIdongId", memberMap.get("idongId")); // 被关注人
							int attionCount = searchBiz.getIfAttention(paraMap);
							if (idongId > 0) {
								if (attionCount > 0) { // 已关注
									memberMap.put("attionStatus", "1");
								} else { // 关注
									memberMap.put("attionStatus", "2");
								}
							} else { // 关注
								memberMap.put("attionStatus", "2");
							}
						}
					}else{
						map.put("code", 1);
						map.put("result", new ArrayList<Member>());
						return "succ";
					}
				}else {
					map.put("code", 1);
					map.put("result", new ArrayList<Member>());
					return "succ";
				}
			}else{
				map.put("code", 0);
				map.put("msg", "参数缺失");
				return "succ";
			}
			map.put("code", 1);
			// 按距离排序
			SortUtil.nearbySort(persons);
			map.put("result", persons);
			map.remove("list");
			map.put("pageCurrent", totalCount);
			return "succ";
		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", 0);
			map.put("msg", "系统异常");
			return "succ";
		}
	}
	
	/**
	 * 月排行榜
	 * @return
	 */
	@Action(value = "monthranking", results = { @Result(name = "succ", type = "json", params = {"root", "map" }) })
	public String monthRanking(){
		
		double lon = person.getLon(); // 纬度
		double lat = person.getLat(); // 经度
		int idongId = person.getIdongId(); // 爱动号
		
		map = new HashMap<String, Object>();
		try {
			Map<String, Object> page = PageUtil.page(10, pageCurrent);
			map.put("pageCurrent", page.get("pageCurrent"));
			List<Member> members = searchBiz.getMonthRanking(page);
			if(members.size() > 0){
				for (Member member : members) {
					member.setHeadUrl(ReadPropertiesUtil.getIMGREAD(member.getHeadUrl()));
					double dataLon = member.getLon(); // 纬度
					double dataLat = member.getLat(); // 经度
					if(lon > 0 && lat > 0 && dataLon > 0 && dataLat > 0){
						double discance = CountDistance.distance(lon,lat,dataLon,dataLat);
						int	dis = (int) Math.rint(discance); // 四舍五入取整数
						int distance = dis/1000;
						if(distance < 1){
							if(dis <= 100){
								member.setCoordinate("<100m"); // 相距距离
							}else if(100 < dis && dis <= 500){
								member.setCoordinate("<500m"); // 相距距离
							}else if(500 < dis && dis <= 800){
								member.setCoordinate("<800m"); // 相距距离
							}else{
								member.setCoordinate(dis + " m"); // 相距距离
							}
						}else{
							member.setCoordinate(distance + " km"); // 相距距离
						}
					}else{
						member.setCoordinate("未知");
					}
					
					Map<String, Object> paraMap = new HashMap<String, Object>();
					paraMap.put("idongId", idongId); // 关注人
					paraMap.put("tionIdongId", member.getIdongId()); // 被关注人
					int attionCount = searchBiz.getIfAttention(paraMap);
					if (idongId > 0) {
						if (attionCount > 0) { // 已关注
							member.setAttionStatus("1");
						} else { // 关注
							member.setAttionStatus("2");
						}
					} else { // 关注
						member.setAttionStatus("2");
					}
				}
				map.put("code", 1);
				map.put("result", members);
				return "succ";
			}
			map.put("code", 1);
			map.put("result", members);
			return "succ";
		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", 0);
			map.put("msg", "系统异常");
			return "succ";
		}
	}
	
	/**
	 * 附近的人推荐列表
	 * @return
	 */
	@Action(value = "recommendranking", results = { @Result(name = "succ", type = "json", params = {"root", "map" }) })
	public String recommendRanking(){
		
		double lon = person.getLon(); // 纬度
		double lat = person.getLat(); // 经度
		int idongId = person.getIdongId(); // 爱动号
		
		map = new HashMap<String, Object>();
		try {
			Map<String, Object> page = PageUtil.page(12, pageCurrent);
			map.put("pageCurrent", page.get("pageCurrent"));
			List<Member> members = searchBiz.getRecommendRanking(page);
			if(members.size() > 0){
				for (Member member : members) {
					Map<String, Object> taskTags = personalMsgBiz.selectTaskTags(idongId);
					if(taskTags!=null){
						member.setTask1(Integer.parseInt(taskTags.get("task1").toString()));
						member.setTask2(Integer.parseInt(taskTags.get("task2").toString()));
						member.setTask3(Integer.parseInt(taskTags.get("task3").toString()));
						member.setHeadUrl(ReadPropertiesUtil.getIMGREAD(member.getHeadUrl()));
					}
					double dataLon = member.getLon(); // 纬度
					double dataLat = member.getLat(); // 经度
					if(lon > 0 && lat > 0 && dataLon > 0 && dataLat > 0){
						double discance = CountDistance.distance(lon,lat,dataLon,dataLat);
						int	dis = (int) Math.rint(discance); // 四舍五入取整数
						member.setDistance(dis);
						int distance = dis/1000;
						if(distance < 1){
							if(dis <= 100){
								member.setCoordinate("<100m"); // 相距距离
							}else if(100 < dis && dis <= 500){
								member.setCoordinate("<500m"); // 相距距离
							}else if(500 < dis && dis <= 800){
								member.setCoordinate("<800m"); // 相距距离
							}else{
								member.setCoordinate(dis + " m"); // 相距距离
							}
						}else{
							member.setCoordinate(distance + " km"); // 相距距离
						}
					}else{
						member.setCoordinate("未知");
					}
					
					Map<String, Object> paraMap = new HashMap<String, Object>();
					paraMap.put("idongId", idongId); // 关注人
					paraMap.put("tionIdongId", member.getIdongId()); // 被关注人
					int attionCount = searchBiz.getIfAttention(paraMap);
					if (idongId > 0) {
						if (attionCount > 0) { // 已关注
							member.setAttionStatus("1");
						} else { // 关注
							member.setAttionStatus("2");
						}
					} else { // 关注
						member.setAttionStatus("2");
					}
				}
				
				map.put("code", 1);
				map.put("result", members);
				return "succ";
			}
			map.put("code", 1);
			map.put("result", members);
			return "succ";
		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", 0);
			map.put("msg", "系统异常");
			return "succ";
		}
	}
}